package com.web.server.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by QINZHONGCHENG on 2015/10/26.
 */
public class StringUtil {

    /**
     * 判断字符串是否为数字类型
     */
    public static boolean isNumeric(String str) {
        if (str == null || str == "") {
            return false;
        }
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String valueOf(Object obj) {
        return (obj == null) ? null : obj.toString();
    }
    /**
     * 判断给定的对象集合中是否存在 isNullOrEmpty为true的,有则返回true否则返回false by ZhangHao
     * @param objects 对象集合
     * @return
     */
    public static boolean hasNullOrEmpty(Object... objects) {
        for (Object obj : objects) {
            if (StringUtil.isNullOrEmpty(obj)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 判断对象或对象数组中每一个对象是否为�? 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }

        return false;
    }

    /***
     * 校验手机号格�?     * @param mobile
     *
     * @return
     */
    public static boolean isMobileNumber(String mobile) {
        return Pattern.compile("^1\\d{10}$").matcher(mobile).matches();
    }

    /***
     * whether strArray contains j<br> test ok
     *
     * @param strArray
     * @param j
     * @return
     */
    public static int isContains(String[] strArray, String j) {
        int index = Constant.NEGATIVE_ONE;
        if (isNullOrEmpty(strArray)) {
            return index;
        }
        int length2 = strArray.length;
        for (int ii = 0; ii < length2; ii++) {
            String i = strArray[ii];
            if (i == j || (i != null && i.equals(j))) {
                index = ii;
                break;
            }
        }
        return index;
    }

    /***
     * String -->string<br>convert first Letter to LowerCase
     *
     * @param str
     * @return
     */
    public static String title(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    public static int isContains2(String[] strArray, String j) {
        int index = Constant.NEGATIVE_ONE;
        if (isNullOrEmpty(strArray)) {
            return index;
        }
        int length2 = strArray.length;
        for (int ii = 0; ii < length2; ii++) {
            String i = strArray[ii];
            if (i == j || (equalsWildcard(j, i))) {
                index = ii;
                break;
            }
        }
        return index;
    }

    /***
     * 是否包含指定字符�?不区分大小写
     *
     * @param input : 原字符串
     * @param regex
     * @return
     */
    public static boolean contain2(String input, String regex) {
        if (isNullOrEmpty(input)) {
            return false;
        }
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(input);
        boolean result = m.find();
        return result;
    }

    /***
     * @param source
     * @param regex  : 含有通配�?通配符只有一�?*.<br>
     *               *表示任何字符,不限个数
     * @return
     */
    public static boolean equalsWildcard(String source, String regex) {
        regex = regex.replace(".", "\\.");
        regex = regex.replace("*", "(.*)");//加上小括�?方便查看
//		System.out.println(regex);
        Pattern p = Pattern.compile("^" + regex + "$", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(source);
        return m.find();
    }

    /***
     * Delete the brackets
     *
     * @param input
     * @return
     */
    public static String deletebrackets(String input) {
        input = input.replaceAll("\\[?(.*)\\]?", "$1");
        return input;
    }

    /***
     * delete ( and )
     *
     * @param input
     * @return
     */
    public static String deleteSmallBrackets(String input) {
        input = input.replaceAll("\\(?(.*)\\)", "$1");
        return input;
    }

    public static String convertUTF2ISO(String oldName) {
        if (oldName == null) {
            return oldName;
        }
        try {
            return new String(oldName.getBytes(Constant.CHARSET_UTF), Constant.CHARSET_ISO88591);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertGBK2ISO(String input) {
        if (input == null) {
            return input;
        }
        try {
            return new String(input.getBytes(Constant.CHARSET_GBK), Constant.CHARSET_ISO88591);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * convert GBK to UTF-8
     *
     * @param input
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] convertGBK2UTF(byte[] input)
            throws UnsupportedEncodingException {
        return new String(input, Constant.CHARSET_GBK)
                .getBytes(Constant.CHARSET_UTF);
    }

    /***
     * convert from GBK to UTF-8
     *
     * @param input
     * @return
     */
    public static String convertGBK2UTF(String input) {
        if (input == null) {
            return input;
        }
        try {
            return new String(input.getBytes(Constant.CHARSET_GBK), Constant.CHARSET_UTF);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] convertFromeGBK(byte[] input, String toCharset)
            throws UnsupportedEncodingException {
        return new String(input, Constant.CHARSET_GBK).getBytes(toCharset);
    }

    /***
     * convert utf-8 to gbk
     *
     * @param input
     * @return
     */
    public static String convertUTF2GBK(String input) {
        if (input == null) {
            return input;
        }
        try {
            return new String(input.getBytes(Constant.CHARSET_UTF), Constant.CHARSET_GBK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertISO2Specified(String oldName, String newEncoding) {
        if (oldName == null) {
            return oldName;
        }
        try {
            return new String(oldName.getBytes(Constant.CHARSET_ISO88591), newEncoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertISO2GBK(String input) {
        return convertISO2Specified(input, Constant.CHARSET_GBK);
    }

    public static String convertISO2UTF(String oldName) {
        return convertISO2Specified(oldName, Constant.CHARSET_UTF);
    }

    public static int getIntegerFromMap(Map map, String key) {
        int val;
        Object obj = map.get(key);
        if (obj instanceof String) {
            val = Integer.parseInt((String) obj);
        } else {
            val = (Integer) obj;
        }
        return val;
    }

    /***
     * 在最前面的位置插入新的元�?     * @param list
     *
     * @param obj
     * @return
     */
    public static List prepend(List list, Object obj) {
        if (list == null) {
            list = new ArrayList();
        }
        list.add(0, obj);
        return list;
    }

    /**
     * 字符串过�?则使�?�?替换
     *
     * @param input
     * @param length 显示的字符的个数
     * @return
     */
    public static String omitTooLongString(String input, int length) {
        if (input == null || input.trim().equals(Constant.EMPTY)) {
            return input;
        }
        int len = input.length();
        if (len <= length) {
            return input;
        } else {
            input = input.substring(0, length);
            input += Constant.ENGLISH_ELLIPSIS;
        }
        return input;
    }

    /***
     * convert Map to query string
     *
     * @param orderInfo2PayMap
     * @return
     */
    public static String getQueryString(Map orderInfo2PayMap) {
        StringBuffer postData = new StringBuffer();
        if (StringUtil.isNullOrEmpty(orderInfo2PayMap)) {
            return Constant.EMPTY;
        }
        for (Object obj : orderInfo2PayMap.keySet()) {
            Object value = orderInfo2PayMap.get(obj);
            postData.append(obj).append("=").append(value).append("&");
        }

        return postData.toString().substring(0, postData.length() - 1);
    }

    public static Map parseQueryString(String notifyUrl) {
        String extra_common = notifyUrl.split("\\?")[1];
        String[] strs = extra_common.split("&");
        Map map = new HashMap();
        for (int i = 0; i < strs.length; i++) {
            String[] keyVal = strs[i].split("=");
            String val = null;
            if (keyVal.length > 1) {
                val = keyVal[1];
            } else {
                val = Constant.EMPTY;
            }
            map.put(keyVal[0], val);
        }
        return map;
    }

    public static String escapeHTML(String originStr) {
        String resultStr = originStr.substring(0);
        resultStr = resultStr.replace("'", "&apos;");//替换单引�?        resultStr = resultStr.replaceAll("&", "&amp;");//替换&
        resultStr = resultStr.replace("\"", "&quot;"); // 替换双引�?        resultStr = resultStr.replace("\t", "&nbsp;&nbsp;");// 替换跳格
        resultStr = resultStr.replace(" ", "&nbsp;");// 替换空格
        resultStr = resultStr.replace("<", "&lt;");//替换左尖括号
        resultStr = resultStr.replaceAll(">", "&gt;");//替换右尖括号
        return resultStr;
    }

    /**
     * 使用sha1生成签名
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String createSign(String token, String timestamp, String nonce){
        List l = new ArrayList();
        l.add(token);
        l.add(timestamp);
        l.add(nonce);
        Collections.sort(l);
        StringBuilder tmpStr = new StringBuilder();
        for(int i=0;i<l.size();i++){
            tmpStr.append(l.get(i));
        }
        return encrypt(tmpStr.toString(), "SHA-1");
    }

    /**
     * Use Def: encrypt(strSrc, null);
     * Use MD5: encrypt(strSrc, "MD5");
     * Use SHA: encrypt(strSrc, "SHA-1");
     * Use SHA-256: encrypt(strSrc, "SHA-256");
     * @param strSrc
     * @param encType
     * @return
     */
    public static String encrypt(String strSrc, String encType) {
        MessageDigest md = null;
        String strDes = null;

        byte[] bt = strSrc.getBytes();
        try {
            if (encType == null || encType.equals("")) {
                encType = "MD5";
            }
            md = MessageDigest.getInstance(encType);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); //to HexString
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Invalid algorithm.");
            return null;
        }
        return strDes;
    }

    private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
